<?php
/**
 * 工单完结操作
 * User: Administrator
 * Date: 2018\8\8 0008
 * Time: 12:01
 */

namespace app\lib\Order\OrderOption;


use app\lib\Order\IsOrder\IsOrder;
use app\lib\Order\OrderConstructionLog\OrderConstructionLog;
use app\lib\Order\OrderExtensionConfig\GetOrderBindingExtension;
use app\lib\Order\OrderExtensionConfig\OrderBindingEditExtension;
use app\lib\Order\OrderInfo\GetOrderMoney;
use app\lib\Order\OrderInfo\UpdateOrderStatus;
use app\lib\Order\OrderPaymentNotice\OrderNotice;
use app\model\OrderInfoModel;
use app\model\OrderSignRecordModel;

class OrderEndOption
{
    protected $orderId;
    protected $opUid;
    public function __construct($orderId,$opUid)
    {
        $this->opUid   = $opUid;
        $this->orderId = $orderId;
    }

    /**
     * 参数验证
     * @throws \Exception
     */
    protected function check(){
        $isOrder = new IsOrder($this->orderId);
        /*状态是否能完结工单*/
        if(!$isOrder->isExecuteOrder()){
            exception('工单状态异常无法完结');
        }
        /*判断是否存在未交款*/
        $model = (new GetOrderMoney($this->orderId));
        if(!($model->isAllPayMoney())){
            exception('工单存在未交款，工单无法完结');
        }
        /*判断是否存在未审核的签收通知*/
        if((new OrderNotice($this->orderId))->isNoReviewSign()){
            exception('还有签收通知未被审核，工单无法完结');
        }
        /*判断是否存在未签收*/
        $model = (new OrderSignRecordModel());
        $map = [$model->_orderId=>$this->orderId,$model->_status = 0];
        $signId = $model->where($map)->value($model->_id);
        if($signId){
            exception('还存在未签收的信息,工单无法完结');
        }
        return true;
    }

    /**
     * 完结工单操作
     * @return bool
     * @throws \Exception
     */
    public function save(){
        /*修改工单状态*/
        (new UpdateOrderStatus($this->orderId,$this->opUid))->getEndOrderStatus()->save();
        /*获取工单总耗时长*/
        $analysis = (new OrderConstructionLog())->getCycleDayAnalysis();
        /*记录完成时间*/
        $model =  new OrderInfoModel();
        $data = [
            $model->_id=>$this->orderId,
            $model->_orderEndTime=>time(),
            /*TODO 新增字段 CycleDayAnalysis*/
            $model->_cycleDayAnalysis = json_encode($analysis),
        ];
        $result = $model->update($data);
        if(!$result){
            exception('完结工单失败');
        }
        /*完结后清除所有工单标签*/
        if((new GetOrderBindingExtension($this->orderId))->isOrderBindingExtension()){
            (new OrderBindingEditExtension($this->orderId,'endOrder','工单完结取消所有标签'))->releaseBinding();
        }
        /*记入工单日志*/
        $log =  new OrderOptionLog($this->orderId);
        $log->setOptionType('ENDORDER');
        $log->setOptionUserId($this->opUid);
        $log->setSubmitParameter('');
        $log->setOptionContent('工单id为'.$this->orderId.'已完工');
        $log->save();
        return true;
    }
}